<?php


namespace app\admin\controller;

use app\common\model\Role as RoleModel;
use app\common\model\PrivilegeCategory as PriCateModel;
use think\Db;
use think\Exception;

class Role extends BaseController
{
    // add
    public function add()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $post = $this->request->post();
            $roleModel = new RoleModel();

            // 判重
            $one = $roleModel->where('name', $post['name'])->find();
            if ($one) {
                return mkRestful(1, '角色名已存在');
            }

            // post privilege id array
            $postPriIdArr = [];
            if (isset($post['privilege_id'])) {
                $postPriIdArr = array_keys($post['privilege_id']);
                unset($post['privilege_id']);
            }

            // 写入
            Db::startTrans();
            try{
                // 角色
                $result = $roleModel->allowField(true)->save($post);
                // 角色权限
                $roleModel->privileges()->saveAll($postPriIdArr);
                Db::commit();
                $return = mkRestful(0, '添加角色成功', 'success');
            } catch (Exception $e) {
                Db::rollback();
                $return = mkRestful(1, $e->getMessage());
            }
            return $return;
        }

        // form page
        $privilegeCategories = PriCateModel::with('privileges')->select();
        $this->assign([
            'title' => '新增角色',
            'privilegeCategories' => $privilegeCategories
        ]);
        return $this->fetch();
    }

    // del
    public function del($model = null)
    {
        return parent::del(new RoleModel());
    }

    // edit
    public function edit()
    {
        $id = $this->request->param('id');
        $role = RoleModel::with('privileges')->find($id);
        $privilegeIdArr = [];
        foreach ($role['privileges'] as $privilege) {
            $privilegeIdArr[] = $privilege['id'];
        }
        if ($this->request->isAjax() && $this->request->isPost()) {
            $post = $this->request->post();

            // post privilege id
            $postPrivilegeIdArr = $priIdArr = [];
            if (isset($post['privilege_id'])) {
                $postPrivilegeIdArr = array_keys($post['privilege_id']);
            }

            // add
            $addPrivilegeIdArr = array_diff($postPrivilegeIdArr, $privilegeIdArr);
            // del
            $delPrivilegeIdArr = array_diff($privilegeIdArr, $postPrivilegeIdArr);

            Db::startTrans();
            try{
                $result = $role->allowField(true)->save($post);
                if ($addPrivilegeIdArr) $role->privileges()->saveAll($addPrivilegeIdArr);
                if ($delPrivilegeIdArr) $role->privileges()->detach($delPrivilegeIdArr);
                Db::commit();
                $return = mkRestful(0, '角色修改成功', 'success');
            } catch (Exception $e) {
                Db::rollback();
                $return = mkRestful(1, $e->getMessage());
            }

            return $return;
        }

        // form page
        $privilegeCategories = PriCateModel::with('privileges')->select();
        $role['privilegeIdArr'] = $privilegeIdArr;
        $this->assign([
            'title' => '修改角色',
            'role' => $role->getData(),
            'privilegeCategories' => $privilegeCategories
        ]);
        return $this->fetch();
    }
    // all
    public function all()
    {
        if ($this->request->isAjax()) {
            $get = $this->request->get();
            $roles = RoleModel::with('privileges')->paginate($get['limit'])->toArray();
            return [
                'code' => 0,
                'msg' => '',
                'count' => $roles['total'],
                'data' => $roles['data']
            ];
        }
        $roles = RoleModel::with('privileges')->select();
        $this->assign([
            'title' => '角色管理',
            'roles' => $roles->hidden(['create_time','update_time','delete_time'])
        ]);
        return $this->fetch();
    }

    // detail
    public function detail($model = null)
    {
        return parent::detail(new RoleModel()); // TODO: Change the autogenerated stub
    }

    public static function getRolesPrivileges($roleIds)
    {
        // 获取用户权限
        $roles = RoleModel::with('privileges')->where('id', 'in', $roleIds)->select();
        $privileges = [];
        foreach ($roles as $role){
            foreach ($role['privileges'] as $privilege) {
                $privilegeStr = $privilege['m'] . '/' . $privilege['c'] . '/' . $privilege['a'];
                $privileges[] = strtolower($privilegeStr);
            }
        }
        return $privileges;
    }
}